# 370100910---建筑大学道路---数据数据处理
import json
from pyproj import Proj
import rasterio
import math
def changeUTM(lat,lon):
    #首先定义要转换的投影坐标系
    p1 = Proj(proj='utm',zone=50,ellps='WGS84')
    x,y = p1(lon,lat)  # 将地理坐标转换为投影坐标，地理坐标为WGS84下的坐标
    x= round(x/1000,3)
    y = round(y/1000,3)
    return x,y

def compute_elevation(lon, lat):
    elevation = 0
    # 打开SRTM数据文件
    with rasterio.open('sd-dem-90.tif') as dataset:
        # 获取经纬度对应的像素坐标
        row, col = dataset.index(lon, lat)
        # 读取高程数据
        elevation = dataset.read(1)[row, col]
    return elevation
def read_json(data_file):
    new_data = {}
    fclass_arr = []
    road = {}
    with open(data_file, encoding='utf-8') as file:
        content = json.load(file)
        # print(content)
    for item in content['features']:
        coordinates = []
        # print(item)
        properties = item['properties']
        name = properties['name']
        # if name != '经十路':
        #     continue
        # 道路类型
        fclass = properties['fclass']
        # 只选取 trunk, primary, secondary 道路，过滤掉其他
        if fclass not in ['trunk', 'primary']:
            continue
        if fclass not in fclass_arr:
            fclass_arr.append(fclass)
        if name in road:
            coordinates = road[name]
        geometry = item['geometry']
        coordinate = geometry['coordinates'][0]
        lon = coordinate[0]
        lat = coordinate[1]
        x,y = changeUTM(lat,lon)
        elevation = int(compute_elevation(lon, lat))
        one = {
            "type":fclass,
            "lon": coordinate[0],
            "lat": coordinate[1],
            "x": x,
            "y": y,
            "elevation": elevation
        }
        # if len(coordinates)>0:
        #     # 判断当前点，距离<1.2km，则不保存，避免重复，避免已有点
        #     if check_points(coordinates,x,y,1.2):
        #         continue
        coordinates.append(one)
        road[name] = coordinates
        # print(geometry)
    # 稀疏化坐标点
    for name, coords in road.items():
        # print(len(coords))
        if coords:
            # 初始化稀疏坐标列表，先加入第一个点
            sparse_coords = [coords[0]]  
            last_x, last_y = coords[0]['x'], coords[0]['y']
              # 设置距离阈值，单位为千米
            threshold = 5
            for coord in coords[1:]:
                current_x, current_y = coord['x'], coord['y']
                dis = distance(last_x, last_y, current_x, current_y) 
                if dis>= threshold:
                    # print(current_x,current_y)
                    # print("==========",dis)
                    sparse_coords.append(coord)
                    last_x, last_y = current_x, current_y
            # print(sparse_coords)
            # print(len(sparse_coords))
            road[name] = sparse_coords
    print(fclass_arr)
    return road

def distance(x1, y1, x2, y2):
    """ 计算两点之间的欧几里得距离 """
    return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

def check_points(coordinates,x,y,space):
    for point in coordinates:
        x_min = point['x']-space
        x_max = point['x']+space
        y_min = point['y']-space
        y_max = point['y']+space
        # 在矩形内
        if x_min<=x<=x_max and y_min<=y<=y_max:
            return True
    return False


if __name__ == "__main__":
    data_file = "370100910.json"
    road = read_json(data_file)
    print(len(road))
    # for item in road:
    #     print(item)
    #     print(road[item])
    output_file = "roadtest.json"
    with open(output_file, 'w', encoding='utf-8') as file:
        json.dump(road, file,ensure_ascii=False)
    print("数据已保存到", output_file)